package com.zyht.bank.manage.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.zyht.bank.entity.AxdOrgInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.excel.DefaultExcel07Export;
import com.zyht.common.excel.IExport;
import com.zyht.common.excel.IImport;
import com.zyht.common.intercepter.Token;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;

@Controller
@RequestMapping("/admin/org")
public class AdminOrgInfoController extends AbsManageBaseController {
	private String BASEPATH = "/banks/manage/orginfo/";

	@Resource
	private AxdOrgInfoService axdOrgInfoService;


	@Resource(name = "excelImportOrgInfo")
	private IImport<AxdOrgInfo> defaultImport;

	/**
	 * 获取机构
	 * 
	 * @param model
	 * @param currentPage
	 * @param orgName
	 * @return
	 */
	@Token(save = true)
	@RequestMapping(value = "index")
	public String index(Model model, Integer currentPage, String orgCode, HttpSession session) {
		// 获取用户
		SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
		model.addAttribute("msg", "非法的操作！");
		model.addAttribute("redirect", "admin/index");
		if (null == sysUser) {
			return "message";
		}
		Map<String, Object> map = new HashMap<>();
		if (null == currentPage) {
			currentPage = 1;
		}
		if (StringUtils.isNotEmpty(orgCode)) {
			map.put("orgCodeLike", orgCode);
			model.addAttribute("orgCode", orgCode);
		}
		int pageSize = getPageSize();
		PageHelper.startPage(currentPage, pageSize);
		com.github.pagehelper.Page<AxdOrgInfo> pageInfo = (com.github.pagehelper.Page<AxdOrgInfo>) axdOrgInfoService
				.selectByMap(map);
		int total = Long.valueOf(pageInfo.getTotal()).intValue();
		Page<AxdOrgInfo> page = new Page<AxdOrgInfo>(total, currentPage, pageSize);
		page.setRecordList(pageInfo);
		model.addAttribute("page", page);

		return makeView("orgindex");

	}

	/**
	 * 编辑
	 * 
	 * 
	 * @param orgInfoId
	 * @return
	 */
	@Token(save = true)
	@RequestMapping(value = "toedit", method = RequestMethod.GET)
	public String getOne(Integer id, Model model) {

		AxdOrgInfo axdOrgInfo = null;
		if (null != id) {
			axdOrgInfo = axdOrgInfoService.findOneById(id);
		} else {
			axdOrgInfo = new AxdOrgInfo();
		}
		model.addAttribute("bean", axdOrgInfo);
		return makeView("orgedit");

	}

	/**
	 * 保存
	 * 
	 * @param axdOrgInfo
	 * @return
	 */
	@Token(remove = true)
	@RequestMapping(value = "edit/1", method = RequestMethod.POST)
	public String edit(AxdOrgInfo axdOrgInfo, Model model, HttpSession session) {
		AxdOrgInfo axdOrgInfoCheck = (AxdOrgInfo) session.getAttribute("axdOrgInfoCheck");
		model.addAttribute("msg", "非法的操作！");
		model.addAttribute("redirect", "admin/org/index");
		Date date = new Date();
		if (null == axdOrgInfo) {
			return "message";
		}

		if (StringUtils.isEmpty(axdOrgInfo.getOrgCode()) || StringUtils.isEmpty(axdOrgInfo.getOrgName())) {
			return "message";
		}
		try {
			if (axdOrgInfo.getOrgInfoId() != null) {
				// 获取
				AxdOrgInfo axdOrg = axdOrgInfoService.findOneById(axdOrgInfo.getOrgInfoId());
				if (axdOrg == null) {
					return "message";
				}
				if (axdOrgInfoCheck != null && axdOrgInfoCheck.getOrgLevel() != 1
						&& axdOrgInfoCheck.getOrgInfoId() == axdOrg.getOrgInfoId()
						&& axdOrgInfoCheck.getOrgLevel() != axdOrgInfo.getOrgLevel()) {
					return "message";
				}
				axdOrgInfo.setCreateTime(date);
				axdOrgInfo.setStatus(1);
				axdOrgInfoService.updateById(axdOrgInfo);

			} else {
				String orgCode = axdOrgInfo.getOrgCode();
				AxdOrgInfoExample example = new AxdOrgInfoExample();
				example.createCriteria().andOrgCodeEqualTo(orgCode).andStatusEqualTo(1);
				PageHelper.startPage(1, 1);
				List<AxdOrgInfo> list = axdOrgInfoService.list(example);
				if (list.size() > 0) {
					model.addAttribute("msg", "机构已存在，添加失败！");
					model.addAttribute("redirect", "admin/org/index");
					return "message";
				}
				example.clear();
				example.createCriteria().andOrgCodeEqualTo(orgCode).andStatusEqualTo(0);
				PageHelper.startPage(1, 1);
				List<AxdOrgInfo> orgInfos = axdOrgInfoService.list(example);
				if (orgInfos.size() > 0) {
					AxdOrgInfo axdOrg = orgInfos.get(0);
					axdOrg.setStatus(1);
					axdOrg.setCreateTime(date);
					axdOrgInfoService.updateById(axdOrg);

				} else {
					if (axdOrgInfoCheck != null && axdOrgInfoCheck.getOrgLevel() != 1
							&& axdOrgInfoCheck.getOrgLevel() == axdOrgInfo.getOrgLevel()) {
						return "message";
					}
					axdOrgInfo.setStatus(1);
					axdOrgInfo.setCreateTime(date);
					axdOrgInfoService.addOne(axdOrgInfo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "内部异常，操作失败！");
			model.addAttribute("redirect", "admin/org/index");
			return "message";
		}

		model.addAttribute("msg", "操作成功！");
		model.addAttribute("redirect", "admin/org/index");
		return "message";

	}

	/**
	 * 删除
	 * 
	 * @param orgInfoId
	 * @return
	 */
	@Token(remove = true)
	@RequestMapping(value = "edit/2", method = RequestMethod.POST)
	public String del(Integer orgInfoId, Model model, HttpSession session) {
		model.addAttribute("msg", "非法的操作！");
		model.addAttribute("redirect", "admin/org/index");
		if (orgInfoId == null) {
			return "message";
		}
		SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
		Integer orgId = sysUser.getOrgId();
		if (orgId == orgInfoId) {
			return "message";
		}
		AxdOrgInfo axdOrgInfo = axdOrgInfoService.findOneById(orgInfoId);
		if (axdOrgInfo == null) {
			return "message";
		}
		String orgCode = axdOrgInfo.getOrgCode();
		AxdOrgInfoExample example = new AxdOrgInfoExample();
		example.createCriteria().andPcodeEqualTo(orgCode);
		PageHelper.startPage(1, 1);
		List<AxdOrgInfo> list = axdOrgInfoService.list(example);
		if (list.size() > 0) {
			model.addAttribute("msg", "含有子节点删除失败！");
			model.addAttribute("redirect", "admin/org/index");
			return "message";
		}
		try {
			axdOrgInfo.setCreateTime(new Date());
			axdOrgInfo.setStatus(0);
			axdOrgInfoService.updateById(axdOrgInfo);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "内部异常，操作失败！");
			model.addAttribute("redirect", "admin/org/index");
			return "message";
		}
		model.addAttribute("msg", "操作成功！");
		model.addAttribute("redirect", "admin/org/index");
		return "message";

	}

	/**
	 * 导入页面
	 * 
	 * @param file
	 * @param model
	 * @return
	 */
	@RequestMapping("imporv")
	public String doImport() {
		return makeView("imporv");

	}

	/**
	 * 导入
	 * 
	 * @param file
	 * @return
	 */

	@RequestMapping("import")
	public String doImport(MultipartFile file, Model model, HttpServletResponse response) {
		InputStream is = null;
		try {
			is = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("无法读取excel文件:" + file.getOriginalFilename());
			return "redirect:/admin/org/msg/2";
		}
		try {
			this.defaultImport.doImport(is, AxdOrgInfo.class);
		} catch (InvalidFormatException e) {
			e.printStackTrace();
			logger.error("非法的excel文件:" + file.getOriginalFilename());
			return "redirect:/admin/org/msg/3";
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("无法读取excel文件:" + file.getOriginalFilename());
			return "redirect:/admin/org/msg/2";
		}
		return "redirect:/admin/org/msg/1";
	}

	@RequestMapping("msg/{code}")
	public String message(@PathVariable("code") Integer code, HttpServletRequest request, Model model) {
		if (null != code) {
			if (code == 1) {
				model.addAttribute("msg", "导入成功");
			} else if (code == 2) {
				model.addAttribute("msg", "无法读取excel文件");
			} else if (code == 3) {
				model.addAttribute("msg", "非法的excel文件");
			} else {
				model.addAttribute("msg", "操作失败");
			}
		} else {
			model.addAttribute("msg", "操作成功");
		}
		model.addAttribute("redirect", "admin/org/index");
		return "message";
	}

	/**
	 * 导出
	 * 
	 * @param response
	 * @param currentPage
	 * @param orgName
	 * @param orgCode
	 * @param flag
	 */
	@RequestMapping("export")
	public void export(HttpServletResponse response, Integer currentPage, String orgCode, Integer flag) {
		AxdOrgInfoExample example = new AxdOrgInfoExample();
		AxdOrgInfoExample.Criteria criteria = example.createCriteria();
		if (!StringUtils.isNotEmpty(orgCode)) {
			criteria.andOrgCodeLike("%" + orgCode + "%");
		}
		// 判断导出所有还是导出当前页
		// 0: 导出当前页 , null 或者 1, 导出全部
		if (null != flag && flag == 0) {
			if (null == currentPage || currentPage <= 0) {
				currentPage = 1;
			}
			Integer pageSize = getPageSize();
			PageHelper.startPage(currentPage, pageSize);
		}

		List<AxdOrgInfo> bindList = axdOrgInfoService.list(example);
		IExport<AxdOrgInfo> exportBean = new DefaultExcel07Export<>();
		try (OutputStream os = response.getOutputStream()) {
			String fileName = "org_" + System.currentTimeMillis() + "_data";
			response.setContentType(
					"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=ISO8859_1");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "ISO8859_1"));
			exportBean.export(bindList, AxdOrgInfo.class, os);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("JavaIO流异常,原因为:" + e.getMessage());
		}
	}

	private String makeView(String path) {
		return BASEPATH.concat(path);
	}
}
